import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken, setToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.HOST,
  withCredentials: true
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    let token = getToken()
    if (!token) {
      token = ''
    }
    config.headers.token = token
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    return config
  }, error => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应结果拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.errno === 103) {
      MessageBox.alert('系统未登录，请重新登录', '错误', { confirmButtonText: '确定', type: 'error' }).then(() => {
        store.dispatch('WebLogOut').then(() => {})
      })
      return Promise.reject('error')
    } else if (res.errno === 104) {
      console.log(response)
      store.dispatch('NoPermission').then(() => {})
      return Promise.reject('error')
    } else if (res.errno !== 200) {
      Message({
        message: res.errmsg + ' 异常代码：' + res.errno,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(response)
    }
    if (response.headers.token) {
      // 重新设置token
      setToken(response.headers.token)
    }
    return response.data.data
  }, error => {
    Message({
      message: error + '（请联系系统管理员）',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
